package com.campus.server.dao;

import com.campus.common.util.DBUtil;
import com.campus.common.vo.BankAccount;
import com.campus.common.vo.BankTransaction;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class BankDao {
	// 查询余额
    public double getBalance(String userId) {
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement("SELECT balance FROM bank_account WHERE user_id=?")) {
            ps.setString(1, userId);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                return rs.getDouble("balance");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1; // 查询失败
    }

    // 扣费（余额足够才扣）
    public boolean deductBalance(String userId, double amount) {
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(
                 "UPDATE bank_account SET balance = balance - ? WHERE user_id=? AND balance >= ?")) {
            ps.setDouble(1, amount);
            ps.setString(2, userId);
            ps.setDouble(3, amount);
            return ps.executeUpdate() > 0;  // 返回是否更新成功
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    // 充值
    public boolean recharge(String userId, double amount) {
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(
                 "UPDATE bank_account SET balance = balance + ? WHERE user_id=?")) {
            ps.setDouble(1, amount);
            ps.setString(2, userId);
            return ps.executeUpdate() > 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    // 新建账户
    public boolean createAccount(String userId, double initBalance, String password) {
    	if (findAccountById(userId) != null) {
            return false; // 已存在账户，不允许重复开
        }
    	
    	try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(
                 "INSERT INTO bank_account(user_id, balance, password) VALUES (?, ?, ?)")) {
            ps.setString(1, userId);
            ps.setDouble(2, initBalance);
            ps.setString(3, password);
            return ps.executeUpdate() > 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    
    // 撤销账户
    public boolean deleteAccount(String userId, String password) {
    	BankAccount account = findAccountById(userId);
        if (account == null) {
            return false; // 账户不存在
        }
        if (!account.getPassword().equals(password)) {
            return false; // 密码错误
        }

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(
                 "DELETE FROM bank_account WHERE user_id=?")) {
            ps.setString(1, userId);
            return ps.executeUpdate() > 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    

    // 查询流水
    public List<BankTransaction> getTransactions(String userId) {
        List<BankTransaction> list = new ArrayList<>();
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(
                 "SELECT id, user_id, type, amount, create_time FROM bank_transaction WHERE user_id=? ORDER BY create_time DESC")) {
            ps.setString(1, userId);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                BankTransaction tx = new BankTransaction();
                tx.setId(rs.getInt("id"));
                tx.setUserId(rs.getString("user_id"));
                tx.setType(rs.getString("type"));
                tx.setAmount(rs.getDouble("amount"));
                tx.setCreateTime(rs.getTimestamp("create_time"));
                list.add(tx);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
    
    // 插入交易流水
    public void insertTransaction(String userId, String type, double amount) {
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(
                 "INSERT INTO bank_transaction(user_id, type, amount, create_time) VALUES (?, ?, ?, Now())")) {
            ps.setString(1, userId);
            ps.setString(2, type);
            ps.setDouble(3, amount);
            ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public BankAccount findAccountById(String userId) {
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(
                 "SELECT user_id, balance, password FROM bank_account WHERE user_id=?")) {
            ps.setString(1, userId);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                BankAccount account = new BankAccount();
                account.setUserId(rs.getString("user_id"));
                account.setBalance(rs.getDouble("balance"));
                account.setPassword(rs.getString("password")); // 直接取密码
                return account;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null; // 未找到或查询失败
    }


}
